/**
 * Created by zz on 2017/3/28.
 */
var repeatedCheck = false;
var isSameActor = false;
var actorIds,
    actorNames;

$.getActorId = function (data) {
    var actorId = 0;
    if (data.indexOf("1") >= 0)
        actorId = 1;
    else actorId = 2;
    return actorId;
};

var gActorId = $.getActorId(gUserLoginResult.userActors);
var gMainDT2;
if (gActorId != 1)
    $("#ul").hide();
$("#otherUser").click(function () {
    if (gActorId != 1) {
        $.alert("无访问权限", 2)
    } else {
        $("#otherUser").attr("href", "#all_user_tables");
    }
});

$(function () {
    gMainDT = $("#mainDataTables").DataTable({
        ajax: {
            url: "../rds_user/getUser4DT",
            type: "POST",
            data: function (d) {
                d.search = $('#mainDataTables').DataTable().search(this.value);
                d.orgId = gUserLoginResult.orgId;
                d.actorId = gActorId;
            }
        },
        columns: [{
            data: "userId",
            render: function (data, type, row, meta) {
                var checkId = "checkbox" + (parseInt(meta.row) + 1);
                return "<input type='checkbox' class='userCheckBox' value='" + data + "' id='" + checkId + "'>";
            }
        }, {
            data: null,
            targets: 0
        }, {
            data: "loginName"
        }, {
            data: "userName"
        }, {
            data: "userSex",
            render: function (data, type, row) {
                if (data == '男')
                    return "<button class='btn bg-olive btn-xs btn-flat' title='男'>男</button>";
                else
                    return "<button class='btn bg-orange btn-xs btn-flat' title='女'>女</button>";
            }
        }, {
            data: "orgName"
        }, {
            data: "userMobile"
        }, {
            data: "userActors"
        }, {
            data: "userState",
            render: function (data, type, row) {
                if (data == 0)
                    return "<button class='btn btn-default btn-xs btn-flat' >正常</button>";
                if (data == 1)
                    return "<button class='btn btn-danger btn-xs btn-flat' >停用</button>";
            }
        }, {
            data: "userId",
            render: function (data, type, row) {
                // 左侧工具栏按钮的权限
                var buttonDeactivate = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.deactivateUser(" + data + "," + row.userState + ",2)' title='停启用'><i class='fa fa-asterisk'></i></button>";
                var buttonUpdate = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.editUserModal(" + JSON.stringify(row) + ")' title='编辑'><i class='fa fa-edit'></i></button>";
                var buttonDelete = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.deleteUser(" + data + ")' title='删除'><i class='fa fa-user-times'></i></button>";
                var buttonOperation = "";
                buttonOperation += "<button class='btn btn-primary btn-xs btn-flat' onclick='$.getMainOrg(" + row.orgId + ")' title='查看监管单位' ><i class='fa  fa-search'></i></button> ";
                gUpdate == 0 ? buttonOperation : buttonOperation += buttonUpdate + " ";
                gDelete == 0 ? buttonOperation : buttonOperation += buttonDeactivate + " ";
                gDelete == 0 ? buttonOperation : buttonOperation += buttonDelete;
                buttonOperation == "" ? buttonOperation = "无权限" : buttonOperation;
                return buttonOperation;
            }
        }],
        dom: "<'row'<'col-md-4'l><'#mainToolbar.col-md-8'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'>";
            strToolBar += "<div class='btn-group'><button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>";
            strToolBar += "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>";
            strToolBar += "<span class='caret'></span><span class='sr-only'>切换下拉</span></button><ul class='dropdown-menu'>"
            strToolBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button></li>";
            var buttonInsert = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.addUserModal(3)'><i class='fa fa-plus-square'></i> 添加</button></li>";
            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.deactivateUser(0,0,2)'><i class='fa fa-minus-square'></i> 停用</button></li>";
            buttonDelete += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.deactivateUser(0,1,2)'><i class='fa fa-check-square-o'></i> 启用</button></li>";
            gInsert == 0 ? strToolBar : strToolBar += buttonInsert;
            gDelete == 0 ? strToolBar : strToolBar += buttonDelete;
            strToolBar += "</ul></div> <div class='input-group input-group-sm'><input type='text' class='form-control' name='searchText' placeholder='账号 / 姓名 / 公司'>";
            strToolBar += "<span class='input-group-btn'><button class='btn btn-primary btn-flat' type='button' onclick='$(this).searchDT()'><i class='fa fa-search'></i></button></span></div></div>";
            $("#mainToolbar").append(strToolBar);
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(1).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

    gMainDT2 = $("#mainDataTables2").DataTable({
        ajax: {
            url: "../rds_user/getUser4DT",
            type: "POST",
            data: function (d) {
                d.search = "";
                d.orgId = gUserLoginResult.orgId;
                d.actorId = 2;
            }
        },
        columns: [{
            data: "userId",
            render: function (data, type, row, meta) {
                if (data == gUserLoginResult.userId)
                    return null;
                var checkId = "checkbox" + (parseInt(meta.row) + 1);
                return "<input type='checkbox' class='userCheckBox2' value='" + data + "' id='" + checkId + "'>";
            }
        }, {
            data: null,
            targets: 0
        }, {
            data: "loginName"
        }, {
            data: "userName"
        }, {
            data: "userSex",
            render: function (data, type, row) {
                if (data == '男')
                    return "<button class='btn bg-olive btn-xs btn-flat' title='男'>男</button>";
                else
                    return "<button class='btn bg-orange btn-xs btn-flat' title='女'>女</button>";
            }
        }, {
            data: "orgName"
        }, {
            data: "userMobile"
        }, {
            data: "userActors"
        }, {
            data: "userState",
            render: function (data, type, row) {
                if (data == 0)
                    return "<button class='btn btn-default btn-xs btn-flat' >正常</button>";
                if (data == 1)
                    return "<button class='btn btn-danger btn-xs btn-flat' >停用</button>";
            }
        }, {
            data: "userId",
            render: function (data, type, row) {
                // 左侧工具栏按钮的权限

                var buttonDeactivate = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.deactivateUser(" + data + "," + row.userState + ",1)' title='停启用'><i class='fa fa-asterisk'></i></button>";
                var buttonUpdate = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.editUserModal(" + JSON.stringify(row) + ")' title='编辑'><i class='fa fa-edit'></i></button>";
                var buttonDelete = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.deleteUser(" + data + ")' title='删除'><i class='fa fa-user-times'></i></button>";
                var buttonOperation = "";
                if (data != gUserLoginResult.userId) {
                    gUpdate == 0 ? buttonOperation : buttonOperation += buttonUpdate + " ";
                    gDelete == 0 ? buttonOperation : buttonOperation += buttonDeactivate + " ";
                    gDelete == 0 ? buttonOperation : buttonOperation += buttonDelete;
                }
                buttonOperation == "" ? buttonOperation = "无权限" : buttonOperation;
                return buttonOperation;
            }
        }],
        dom: "<'row'<'col-md-4'><'#mainToolbar2.col-md-8'>r>t<'row'<'col-md-6'><'col-md-6'>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar2").empty();
            var strToolBar = "<div class='pull-right'>";
            if (gActorId == 1)
                strToolBar += "<button class='btn btn-primary btn-sm btn-flat' onclick='$.addUserModal(1)'><i class='fa  fa-user-plus'></i> 添加系统管理员</button> ";
            strToolBar += "<div class='btn-group'><button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>";
            strToolBar += "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>";
            strToolBar += "<span class='caret'></span><span class='sr-only'>切换下拉</span></button><ul class='dropdown-menu'>"
            strToolBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='gMainDT2.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button></li>";
            var buttonInsert = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.addUserModal(2)'><i class='fa fa-plus-square'></i> 添加</button></li>";
            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.deactivateUser(0,0,1)'><i class='fa fa-minus-square'></i> 停用</button></li>";
            buttonDelete += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.deactivateUser(0,1,1)'><i class='fa fa-check-square-o'></i> 启用</button></li>";
            gInsert == 0 ? strToolBar : strToolBar += buttonInsert;
            gDelete == 0 ? strToolBar : strToolBar += buttonDelete;
            if (gUserLoginResult.orgType == 0) {
                strToolBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.getMainOrg(" + gUserLoginResult.orgId + ")'>查看监管单位</button></li>";
            }
            $("#mainToolbar2").append(strToolBar);
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(1).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });


    if (gUpdate == 0 && gDelete == 0 && gInsert == 0) {
        var oTable = $('#mainDataTables2').dataTable();
        oTable.fnSetColumnVis(0, false);//隐藏列
        oTable.fnSetColumnVis(9, false);
    }
});

// 搜索框查询操作
$.fn.searchDT = function () {
    // 注意gSelect查询权限的处理，由该表是否存在添加人或者审核人决定
    var searchContext = $("input[name='searchText']").val();
    gMainDT.search(searchContext).draw();
};

//本公司用户查询
$.fn.searchDT2 = function () {
    // 注意gSelect查询权限的处理，由该表是否存在添加人或者审核人决定
    var searchContext = $("input[name='searchText2']").val();
    gMainDT2.search(searchContext).draw();
};

// DT头部的复选按钮全选操作
$.checkChange = function (t) {
    var isChecked;
    if (t == 1) {
        isChecked = $("#batch_check").prop('checked');
        $(".userCheckBox").prop("checked", isChecked);
    } else if (t == 11) {
        isChecked = $("#batch_check2").prop('checked');
        $(".userCheckBox2").prop("checked", isChecked);
    }
    else {
        isChecked = $("#actor_check").prop('checked');
        $(".actorCheckBox").prop("checked", isChecked);
    }
};

$.deleteUser = function (userId) {
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">是否要删除该用户</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: "../rds_user/deleteUserById",
                    type: 'post',
                    async: false,
                    data: {"userId": userId},
                    success: function (msg) {
                        if (msg != null && typeof (msg) != "undefined") {
                            if (msg.isSuccess == true) {
                                if (msg.jsonData > 0) {
                                    $.alert("操作成功", 1);
                                    gMainDT2.ajax.reload(null, false);
                                    gMainDT.ajax.reload(null, false);
                                }
                                else
                                    $.alert("操作失败", 2);
                            } else
                                $.alert("该账户存在绑定数据 删除失败", 2)
                        }
                    }
                })
            }
        }
    })

};

$.getMainOrg = function (orgId) {
    $.ajax({
        url: "../rds_org/getMainOrgNameAndId",
        type: "post",
        data: {
            "orgId": orgId
        },
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                if (msg.isSuccess) {
                    var mainOrgs = msg.jsonData;
                    $("#mainOrgList").empty();
                    $.each(mainOrgs, function (i, data) {
                        $("#mainOrgList").append("<li>" + data.orgName + "</li>");
                    })
                    if (mainOrgs.length == 0) {
                        $("#mainOrgList").append("<h3>无监管单位</h3>")
                    }
                }
            }
        }
    });

    $("#modal-mainOrg").modal({
        show: true
    })
};


$.getActor4Select = function () {
    $.ajax({
        url: '../rds_user/getActor4Select',
        type: 'post',
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                actors = msg.jsonData;
                var actorRemarks;
                for (var i = 0; i < actors.length; i++) {
                    if (actors[i].actorRemarks == null || actors[i].actorRemarks == "")
                        actorRemarks = "暂无";
                    else
                        actorRemarks = actors[i].actorRemarks.length();
                    $("#tbody").append('<tr role="row"  ><td><input type="checkbox" class="actorCheckBox" actorid=' + actors[i].actorId + ' name=' + actors[i].actorName + '></td><td>' + actors[i].actorName + '</td><td>' + actorRemarks + '</td></tr>');
                }
                $("#orgId").select2();
            }
        }

    })
};

$.getActor4Select();

$.fn.modal.Constructor.prototype.enforceFocus = function () {
};

//删除分组
$.deactivateUser = function (userIds, userState, type) {
    var count = 1,
        str = "",
        data;
    if (userIds == 0) {
        var count = $("input:checkbox[id^='checkbox']:checked").length;
        if (count == 0) {
            if (userState == 0)
                $.alert("请选择要停用的用户", 2);
            else
                $.alert("请选择要启用的用户", 2);
            return;
        } else {
            userIds = "";
            $("input:checkbox[id^='checkbox']:checked").each(function () {
                userIds += $(this).val() + ",";
            });
            userIds = userIds.substring(0, userIds.length - 1);
        }
    }
    if (userState == 0) {
        str = '确定停用该' + count + '个用户吗?';
        data = {"userIds": userIds, "userState": 0}
    }
    else {
        str = '确定启用该' + count + '个用户吗?';
        data = {"userIds": userIds, "userState": 1}
    }
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">' + str + '</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: '../rds_user/deactivateUserById',
                    type: 'post',
                    dataType: 'json',
                    data: data,
                    success: function (msg) {
                        if (msg != null && typeof (msg) != "undefined") {
                            if (msg.isSuccess == true) {
                                if (msg.jsonData > 0) {
                                    $.alert("数据操作成功", 1);
                                    if (type == 1)//本公司用户页面
                                        gMainDT2.ajax.reload(null, false);
                                    else
                                        gMainDT.ajax.reload(null, false);
                                } else {
                                    $.alert("数据操作失败", 2);
                                }
                            } else {
                                $.alert("数据操作失败", 2);
                            }
                        } else {
                            $.alert('系统错误，请联系管理员', 2);
                        }
                    },
                    error: function (msg) {
                        $.alert('系统错误，请联系管理员', 2);
                    }
                });
            }
        }
    });
};

$("#loginName").focus(function () {
    $("#small").hide();
});

$("#loginName").blur(function (e) {
    e.preventDefault();
    var $input = $(e.target);
    var mydata = $input.val();
    $.ajax({
        url: "../rds_user/getCountByLoginName",
        type: 'post',
        dataType: 'json',
        data: {
            "loginName": mydata
        },
        success: function (msg) {
            if (msg.isSuccess == true) {
                if (msg.jsonData != 0) {
                    $("#small").show();
                    repeatedCheck = false;
                } else
                    repeatedCheck = true;
            }
        }
    })
});

$("#orgId").change(function () {
    isSameActor = false;
    if ($("#orgId").find("option:selected").attr("type") == 1) {
        $("#myActor").val("主管管理员");
        $("#setActor").hide();
        actorIds = 7;
        actorNames = "主管管理员"
    } else {
        $("#myActor").val("");
        $("#setActor").show();
        actorIds = "";
        actorNames = "";
    }
});

$("#resetPsw").click(function () {
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">是否将密码重置为666666</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: "../rds_user/resetPswByUserId",
                    async: false,
                    data: {"userId": $("#userId").val()},
                    success: function (msg) {
                        if (msg != null && typeof (msg) != "undefined") {
                            if (msg.isSuccess == true)
                                if (msg.jsonData > 0)
                                    $.alert("操作成功", 1);
                                else
                                    $.alert("操作失败", 2);
                        } else
                            $.alert("操作失败", 2);
                    }
                })
            }
        }
    });
});

$.addUserModal = function (type) {
    $("#resetPsw").hide();
    actorIds = "";
    isSameActor = false;
    isEdit = false;
    $("#password").show();
    $("#small").hide();
    $("#male").val("男");
    $("#female").val("女");
    $("#loginName").attr("disabled", false);
    $("#loginPwd").val('666666');
    $("#userState").val('0');
    document.getElementsByName("mySex")[0].checked = true;
    //添加系统管理员
    if (type == 1) {
        $("#orgId").val(gUserLoginResult.orgId);
        $("#orgSelect").hide();
        $("#myActor").val("系统管理员");
        $("#setActor").hide();
        actorIds = 1;
    } else if (type == 2) {//添加本公司员工
        $("#orgId").val(gUserLoginResult.orgId);
        $("#orgSelect").hide();
        $("#setActor").show();
    } else {
        $("#orgId").val(0).trigger('change');
        $("#orgSelect").show();
        $("#setActor").show();
        $("#orgId").attr("disabled", false);
        $("#orgId").val(0);
    }
    $("#label-user").text("添加用户");
    $("#modal-user").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

// 编辑信息
$.editUserModal = function (jsonData) {
    $("#orgSelect").show();
    $("#small").hide();
    $("#resetPsw").show();
    isEdit = true;
    $.ajax({
        url: '../rds_user/getActorNameByUserId',
        type: 'post',
        data: {'userId': jsonData.userId},
        dataType: 'json',
        success: function (msg) {
            if (msg.isSuccess == true) {
                actorNames = msg.jsonData;
                $("#myActor").val(actorNames);
            }
        }
    });
    $("#male").val("男");
    $("#female").val("女");
    $("#userId").val(jsonData.userId);
    $("#userIcon").attr("src", jsonData.userIcon);
    $("#loginName").val(jsonData.loginName);
    $("#loginName").attr("disabled", true);
    $("#password").hide();
    if (jsonData.userSex == "男") {
        document.getElementsByName("mySex")[0].checked = true;
    }
    else {
        document.getElementsByName("mySex")[1].checked = true;
    }
    $("#orgId").val(jsonData.orgId);
    $("#orgId").val(jsonData.orgId).trigger('change');
    $("#userName").val(jsonData.userName);
    $("#userMobile").val(jsonData.userMobile);
    $("#userEmail").val(jsonData.userEmail);
    $("#userState").val(jsonData.userState);
    $("#userRemarks").val(jsonData.userRemarks);
    $("#label-user").text("编辑信息");
    $("#modal-user").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
    isSameActor = true;
};

// 添加和编辑处理
$('#form-user').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        loginName: {
            validators: {
                notEmpty: {message: '账号不能为空'},
                regexp: {regexp: /^[a-zA-Z0-9_\.]+$/, message: '只能是字母、数字和下划线'},
                stringLength: {min: 6, max: 30, message: '长度必须在6到30之间'}

            }
        }, userName: {
            validators: {
                stringLength: {min: 1, max: 80, message: '长度限制80'},
                notEmpty: {message: '姓名不能为空'}
            }
        },
        userMobile: {
            validators: {
                stringLength: {min: 1, max: 20, message: '长度限制20'},
                notEmpty: {message: '联系电话不能为空'},
                regexp: {
                    regexp: /^[0-9/-]+$/,
                    message: '号码只能包含数字和中划线'
                },
            }
        },
        userEmail: {
            validators: {
                stringLength: {min: 0, max: 50, message: '长度限制50'},
                emailAddress: {message: '邮箱地址不正确'}
            }
        },
        userRemarks: {
            validators: {
                stringLength: {min: 0, max: 200, message: '长度限制200'}
            }
        }
    }
}).on('success.form.bv', function (e) {
    e.preventDefault();
    $("#userSex").val($("input:radio[name='mySex']:checked").val());
    var $form = $(e.target);
    var mydata = $form.serialize();
    mydata += "&orgId=" + $('#orgId').val() + "";
    var formAction = "../rds_user/addUser";
    if (isEdit == true) {
        formAction = "../rds_user/updateUserByUserId";
        repeatedCheck = true;
    }
    else
        mydata += "&userCreateTime=" + $.getTime() + "";
    if (isSameActor == false)
        mydata += "&userActors=" + actorIds + "";
    if (actorNames == "") {
        $.alert("角色未分配", 2);
    } else if (repeatedCheck) {
        $.ajax({
            url: formAction,
            type: 'post',
            data: mydata,
            dataType: 'json',
            success: function (msg) {
                if (msg != null && typeof (msg) != "undefined") {
                    if (msg.isSuccess == true) {
                        if (msg.jsonData > 0) {
                            $.alert("数据操作成功", 1);
                            $.clearModal($('#form-user'), $('#modal-user'));
                            gMainDT.ajax.reload(null, false);
                            gMainDT2.ajax.reload(null, false);
                        } else {
                            $.alert("数据操作失败", 2);
                        }
                    } else {
                        $.alert("数据操作失败", 2);
                        $.clearModal($('#form-user'), $('#modal-user'));
                    }
                } else {
                    $.alert('系统错误，请联系管理员', 2);
                    $.clearModal($('#form-user'), $('#modal-user'));
                }
            },
            error: function (msg) {
                $.alert('系统错误，请联系管理员', 2);
                $.clearModal($('#form-user'), $('#modal-user'));
            }
        });
    } else
        $.alert('账号已被占用', 2);
});

var getOrg = $.ajax({
    url: "../rds_org/getOrgNameAndId",
    type: "POST",
    success: function (Data) {
        var data4Select = Data.jsonData;
        var len = data4Select.length;
        $("#orgId").empty();
        $("#orgId").append('<option value=0>' + '请选择' + '</option>');
        var icon;
        for (var i = 0; i < len; i++) {
            if (data4Select[i].orgType == 1)
                icon = "Ⅰ";
            else
                icon = "Ⅱ";
            $("#orgId").append('<option type=' + data4Select[i].orgType + ' value=' + data4Select[i].orgId + '>' + icon + '&nbsp;' + data4Select[i].orgName + '</option>');
        }
    }
});

$.getTime = function () {
    $.changeTimeType = function (date) {
        if (date >= 0 && date <= 9) {
            date = "0" + date;
        }
        return date;
    };
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = $.changeTimeType(date.getMonth() + 1);
    var strDate = $.changeTimeType(date.getDate());
    var hour = $.changeTimeType(date.getHours());
    var minutes = $.changeTimeType(date.getMinutes());
    var seconds = $.changeTimeType(date.getSeconds());

    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + hour + seperator2 + minutes
        + seperator2 + seconds;
    return currentdate;
};

$.setActor = function () {
    actorIds = "";
    actorNames = "";
    var count = $(".actorCheckBox:checked").length;
    if (count == 0) {
        actorIds = "noActor";
        $.alert("角色未分配", 2);
    } else {
        actorIds = "";
        $(".actorCheckBox:checked").each(function () {
            actorIds += $(this).attr("actorid") + ",";
            actorNames += $(this).attr("name") + "/";
        });
        actorIds = actorIds.substring(0, actorIds.length - 1);

        actorNames = actorNames.substring(0, actorNames.length - 1);
        $("#modal-setActor").modal("hide");
        isSameActor = false;
        if (actorNames == $("#myActor").val())
            isSameActor = true;
        else
            $("#myActor").val(actorNames);

        $("#actor_check").prop("checked", false);
        $(".actorCheckBox").prop("checked", false);
    }
};

$.showSetActorModal = function (data) {
    var actor = new Array();
    actor = data.split("/");
    var len = actor.length;
    for (var i = 0; i < len; i++) {
        $("input[name='" + actor[i] + "']").prop("checked", "checked");
    }
    $("#modal-setActor").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

$("#setActor").click(function () {
    $.showSetActorModal($("#myActor").val());
});

$.cleanActorModal = function () {
    $("#actor_check").prop("checked", false);
    $(".actorCheckBox").prop("checked", false);
    $.clearModal($('#form-actor'), $('#modal-setActor'));
};